﻿@using System.ComponentModel
@using System.ComponentModel.DataAnnotations
@using System.Net.Http.Headers


@page "/admin/article/add"
@page "/admin/article/add/{Id:int}"
@layout AdminLayout

@* 依赖注入 *@
@inject HttpClient Http
@inject IJSRuntime JSRuntime
@inject MessageService _message
@inject NavigationManager navigationManager


<PageTitle>添加文章</PageTitle>


@* 面包屑 *@
<Breadcrumb Style="margin: 16px 0;">
    <BreadcrumbItem>admin</BreadcrumbItem>
    <BreadcrumbItem>articleadd</BreadcrumbItem>
</Breadcrumb>

<Row Justify="space-around" Align="middle" style="background-color: white;padding: 15px 0;">
    <Col Span="22">
    <Form Layout="FormLayout.Horizontal" Model="@articleModel" OnFinish="OnFinish" OnFinishFailed="OnFinishFailed"
        style="margin: 15px 2px;">

        <FormItem Label="标题">
            <Input @bind-Value="@context.Title" />
        </FormItem>

        <FormItem Label="概述">
            <TextArea id="desc" Rows="5" @bind-Value="@context.Description" />
        </FormItem>

        <FormItem Label="分类">
            <Select DataSource="@_categories2" @bind-Value="@context.Cate_id" ValueName="@nameof(Category2.Id)"
                LabelName="@nameof(Category2.Name)" Placeholder="请选择分类" AllowClear>
            </Select>
        </FormItem>

        <FormItem Label="内容">
            <div id="md-editor" style="z-index: 999;">
                <textarea style="display:none;"></textarea>
            </div>
        </FormItem>

        <FormItem>
            <Button Type="@ButtonType.Primary" HtmlType="submit" style="margin-left: 40px;">
                提交
            </Button>
        </FormItem>
    </Form>
    </Col>
</Row>



@code {
    /// <summary>
    /// 接收id路径参数
    /// </summary>
    [Parameter]
    public int Id { get; set; }

    public class Category
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class Category2
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }

    public class ArticleAdd
    {
        public string Title { get; set; }
        public string Description { get; set; }
        public string Cate_id { get; set; }
        public string Content { get; set; }
    }

    public class ArticleDto
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public string Content { get; set; }
        public int Created_at { get; set; }
        public int Updated_at { get; set; }
        public Category Category { get; set; }
    }

    /// <summary>
    /// 接收响应数据，List<T>
    /// </summary>
    public class RespData<T> where T : new()
    {
        public int Code { get; set; }
        public string Msg { get; set; }
        public List<T> Data { get; set; } = new List<T>();
    }

    /// <summary>
    /// 接收响应数据，T
    /// </summary>
    public class RespData2<T> where T : new()
    {
        public int Code { get; set; }
        public string Msg { get; set; }
        public T Data { get; set; } = new T();
    }

    private ArticleAdd articleModel = new ArticleAdd();
    //private List<Category> _categories = new List<Category>();
    private List<Category2> _categories2 = new List<Category2>();


    /// <summary>
    /// 表单提交事件
    /// </summary>
    /// <param name="editContext"></param>
    /// <returns></returns>
    private async Task OnFinish(EditContext editContext)
    {
        // 调用js获取Markdown格式文章内容
        var htmlContent = await JSRuntime.InvokeAsync<string>("getMdMarkdownContent");
        // 创建请求
        var requestMessage = new HttpRequestMessage()
        {
            Method = new HttpMethod("POST"),
            RequestUri = new Uri($"{Utils.BASE_URL}/api/article"),
            Content = JsonContent.Create(
        new
        {
            Title = articleModel.Title,
            Description = articleModel.Description,
            Cate_id = int.Parse(articleModel.Cate_id),
            Content = htmlContent
        }),
        };

        // 获取浏览器localStorage存储的token
        LocalStorageHelper localStorageHelper = new LocalStorageHelper(JSRuntime);
        string token = await localStorageHelper.GetLocalStorage("token");
        // 判断是否有token
        if (!string.IsNullOrEmpty(token))
        {
            // 添加token到请求头
            requestMessage.Headers.Authorization = new AuthenticationHeaderValue(token);
            // 发出请求
            var response = await Http.SendAsync(requestMessage);

            // 读取响应并反序列化
            var resData = await response.Content.ReadFromJsonAsync<RespData2<ArticleDto>>();

            if (resData != null && resData.Code != 200) // 添加失败
            {
                _message.Error("新增文章失败");
                _message.Error(resData.Msg);
            }
            else
            {
                _message.Success("文章新增成功");
                navigationManager.NavigateTo("/admin/articles");
            }
        }
        else
        {
            _message.Info("未登录，请登录后再试");
            // 重定向到登录页
            navigationManager.NavigateTo("/admin/login", true);
        }
    }

    private void OnFinishFailed(EditContext editContext)
    {

    }

    protected override async Task OnInitializedAsync()
    {
        var cateRes = await Http.GetFromJsonAsync<RespData<Category>>("/api/categories");
        if (cateRes != null && cateRes.Data != null)
        {
            // _categories = cateRes.Data;
            cateRes.Data.ForEach(c => _categories2.Add(new Category2 { Id = c.Id.ToString(), Name = c.Name }));
        }

        if (Id > 0)
        {
            var artRes = await Http.GetFromJsonAsync<RespData2<ArticleDto>>($"/api/article/{Id}/edit");
            if (artRes != null)
            {
                if (artRes.Code == 200)
                {
                    var article = artRes.Data;
                    articleModel.Title = article.Title;
                    articleModel.Description = article.Description;
                    articleModel.Cate_id = article.Category.Id.ToString();
                    await JSRuntime.InvokeVoidAsync("setMarkdown2", article.Content);
                }
                else
                {
                    _message.Error("文章信息获取失败");
                    _message.Error(artRes.Msg);
                }
            }
        }
        else
        {
            // 调用js初始化Markdown编辑器
            await JSRuntime.InvokeVoidAsync("initMdEditor");
        }

        await base.OnInitializedAsync();
    }
}
